package com.dfhc.tag;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.jsp.JspException;
import javax.servlet.jsp.JspTagException;
import javax.servlet.jsp.tagext.BodyTagSupport;
import javax.servlet.jsp.tagext.DynamicAttributes;

import org.apache.commons.collections.CollectionUtils;
import org.quickbundle.config.RmConfig;

import com.alibaba.fastjson.JSON;
import com.dfhc.ISystemConstant;
import com.dfhc.securitydb.service.SecurityDBClientService;
import com.dfhc.util.StringHelper;
import com.dfhc.util.TemplateHelper;

import freemarker.template.TemplateException;
/**
 * 扩展字段标签
 * @author 龙色波
 *
 */
public class FrameworkExtendFieldTag extends BodyTagSupport implements DynamicAttributes {
    /**
	 * 
	 */
	private static final long serialVersionUID = -2325901635553530871L;
	private Map attributesMap = new HashMap();
 
    @Override
    public void setDynamicAttribute(String uri, String name, Object value) throws JspException {
        this.attributesMap.put(name, value);
    }
   
    private String buildSelectHTML() throws IOException, TemplateException {	
		//获取表名,过滤值
		String tableName = (String)attributesMap.get(ISystemConstant.TAG_TABLE_NAME);
		String filterValue = (String)attributesMap.get(ISystemConstant.TAG_FILTER_VALUE);
		String fieldsValue =(String)attributesMap.get(ISystemConstant.TAG_FIELDS_VALUE);
		if(StringHelper.isEmpty(tableName)){
			throw new IOException("缺少表名属性！");
		}
		//查安全库，获取对应表扩展字段配置
		//尝试登录安全库
        String sessionId = SecurityDBClientService.getInstance().login(RmConfig.getSingleton().getSecuritydbuser(), RmConfig.getSingleton().getSecuritydbpassword(), RmConfig.getSingleton().getSecuritydbname());
        if(!StringHelper.isEmpty(sessionId)){
	    	try{	
	    		Map<String, Object> searchVo = new HashMap<String,Object>();
	    		searchVo.put("TABLE_NAME", tableName);
	    		if(!StringHelper.isEmpty(filterValue)){
	    			searchVo.put("FILTER_EXPRESSION", filterValue);
	    		}
				List<Map> maps = SecurityDBClientService.getInstance().search(sessionId, "RM_FIELD_EXTENSION", searchVo);
	    		if(CollectionUtils.isEmpty(maps)){
	    			throw new IOException("找不到记录!参数tableName："+tableName+",filterValue:"+filterValue);
	    		}
	    		Map m = maps.get(0);
	    		DynamicTagUtil tagUtil = new DynamicTagUtil();
	    		tagUtil.setServletRequest(pageContext.getRequest());
	    		//去掉表名，过滤值
	    		attributesMap.remove(ISystemConstant.TAG_TABLE_NAME);
	    		attributesMap.remove(ISystemConstant.TAG_FILTER_VALUE);
	    		//替换属性：填写字段值
	    		String controlContent =(String)m.get("CONTROL_CONTENT"); 
	    		if(!StringHelper.isEmpty(fieldsValue)){
	    			//将fieldsValue（JSON格式)转换为Map
	    			Map fieldsMap = JSON.parseObject(fieldsValue, Map.class);
	    			controlContent =TemplateHelper.createContentByString(fieldsMap, controlContent);
	    		}
	    		return tagUtil.parseTags(controlContent, attributesMap);
	    	}finally{
	    		//退出登录
	    		SecurityDBClientService.getInstance().logout(sessionId);
	    	}
	    }else{
	    	throw new IOException("登录安全库失败!");
	    }
    }
   
    @Override
    public int doStartTag() throws JspTagException {
        return EVAL_BODY_BUFFERED;
    }
   
    @Override
    public int doEndTag() throws JspTagException {
        String result = "";
        try {
            result = this.buildSelectHTML();
            super.pageContext.getOut().print(result);
        } catch (Exception e) {
            throw new JspTagException(e.getMessage());
        }
        this.attributesMap.clear();
        return SKIP_BODY;
    }

}
